//
//  ViewController.m
//  AddressBook
//
//  Created by LeeJay on 2017/3/20.
//  Copyright © 2017年 LeeJay. All rights reserved.
//

#import "ViewController.h"
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>

@interface ViewController () <ABPeoplePickerNavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 请求授权
    [self getAuthor];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [self picker];
    
    [self addressBook];
}

// 获取通讯录的部分信息
- (void)picker
{
    // 1. 创建联系人选择控制器
    ABPeoplePickerNavigationController *pvc = [[ABPeoplePickerNavigationController alloc] init];
    
    // 2. 设置代理
    pvc.peoplePickerDelegate = self;
    
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
    {
        ABAddressBookRef bookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(bookRef, ^(bool granted, CFErrorRef error) {
            if (granted)
            {
                NSLog(@"授权成功!");
                [self presentViewController:pvc animated:YES completion:nil];
            }
            else
            {
                NSLog(@"授权失败!");
            }
        });
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
    {
        [self presentViewController:pvc animated:YES completion:nil];
    }
    else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
    {
        NSLog(@"您的通讯录暂未允许访问，请去设置->隐私里面授权!");
    }
}

//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
//{
//
//}

// 选择某个联系人时调用
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(nonnull ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    NSLog(@"选中联系人");
    CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    
    NSString *fir = CFBridgingRelease(firstName);
    NSString *las = CFBridgingRelease(lastName);
    
    NSLog(@"%@---%@", fir, las);
    
    
    ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex count = ABMultiValueGetCount(multi);
    for (int i = 0; i  < count; i++)
    {
        NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(multi, i);
        NSString *phone =(__bridge_transfer NSString *)  ABMultiValueCopyValueAtIndex(multi, i);
        NSLog(@"%@---%@", label, phone);
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

// 取消选中联系人时调用
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)addressBook
{
    // 0. 判断当前的授权状态
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized)
    {
        NSLog(@"请去设置里面授权");
        return;
    }
    
    // 1. 创建通讯录对象
    ABAddressBookRef bookRef = ABAddressBookCreate();
    
    // 2. 获取通讯录中所有的联系人
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(bookRef);
    
    // 3. 遍历所有联系人
    CFIndex count = CFArrayGetCount(arrayRef);
    for (int i = 0; i < count; i++) {
        ABRecordRef record = CFArrayGetValueAtIndex(arrayRef, i);
        
        // 获取姓名
        NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
        NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
        NSLog(@"%@---%@", firstName, lastName);
        
        // 获取电话号码
        ABMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonPhoneProperty);
        CFIndex count = ABMultiValueGetCount(multiValue);
        for (int i = 0; i < count; i ++)
        {
            NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(multiValue, i);
            NSString *phone = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(multiValue, i);
            NSLog(@"%@---%@", label, phone);
            
        }
        CFRelease(multiValue);
    }
    
    // 释放对象
    CFRelease(bookRef);
    CFRelease(arrayRef);
}

- (void)getAuthor
{
    // 判断当前的授权状态是否是用户还未选择的状态
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRef bookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(bookRef, ^(bool granted, CFErrorRef error) {
            if (granted)
            {
                NSLog(@"授权成功!");
            }
            else
            {
                NSLog(@"授权失败!");
            }
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
